// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: tianqiang

#pragma once

namespace coin2::exchange::bybit::order_v3 {

inline int32_t GetErrorCodeAsInt(
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json_error_code) {
  int32_t error_code = 0;
  if (json_error_code.IsInt()) {
    error_code = json_error_code.GetInt();
  } else if (json_error_code.IsString() && std::strlen(json_error_code.GetString()) > 0) {
    error_code = std::stoi(json_error_code.GetString());
  }
  return error_code;
}

inline std::string GetExchangeOrderErrorCode(
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json) {
  if (json.HasMember("retCode")) {
    return std::to_string(GetErrorCodeAsInt(json["retCode"]));
  } else {
    return {};
  }
}

inline std::string GetExchangeOrderErrorMsg(
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json) {
  if (json.HasMember("retMsg")) {
    return json["retMsg"].GetString();
  } else {
    return {};
  }
}

inline coin::proto::OrderErrorCode GetOrderErrorCode(
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json_error_code,
    const rapidjson::GenericValue<rapidjson::UTF8<>>& json_error_msg) {
  using coin::proto::OrderErrorCode;
  auto result = OrderErrorCode::ORDER_UNKNOWN_ERROR;
  int32_t error_code = GetErrorCodeAsInt(json_error_code);
  std::string error_msg = json_error_msg.GetString();
  if (error_code == 0) {
    result = OrderErrorCode::ORDER_NO_ERROR;
  } else if (error_code == 12131) {
    result = OrderErrorCode::SUBMIT_ORDER_INSUFFICIENT_FUND;
  } else if (error_code == 12139) {
    result = OrderErrorCode::ORDER_FILLED_ALREADY;
  } else if (error_code == 12142) {
    result = OrderErrorCode::ORDER_CANCELED_ALREADY;
  } else if ((error_code == 12143) || (error_code == 12407)) {
    result = OrderErrorCode::ORDER_NOT_FOUND;
  } else if ((error_code == 12158) || (error_code == 12218)) {
    result = OrderErrorCode::POST_ONLY_REJECT;
  } else {
    LOG(ERROR) << "[GetOrderErrorCode] " << error_code << ", " << error_msg;
  }

  return result;
}

}  // namespace coin2::exchange::bybit::order_v3
